using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace org.synthful.Windows.Forms
{
    public partial class PopupMenuItem : ToolStripMenuItem
    {
        public PopupMenuItem()
        {
            InitializeComponent();
        }

        public PopupMenuItem(string path, PopupMenu rootPopup)
        {
            InitializeComponent();
            this.RootDropDown = rootPopup;

            this.resolvePath(path);
            //this.DropDown = new ToolStripDropDown();
            if (Directory.Exists(path))
                addPathItems(this, path);
            //this.Click += new EventHandler(whenClicked);
        }

        static protected void addPathItems(PopupMenuItem item, string path)
        {
            string[] dirs = Directory.GetDirectories(path);
            item.DropDown = new PopupMenu();
            //item.DropDown.OwnerItem = item;
            foreach (string d in dirs)
            {
                PopupMenuItem ditem = new PopupMenuItem(d, item.RootDropDown);
                item.DropDown.Items.Add(ditem);
                ditem.RootDropDown = item.RootDropDown;
            }

            string[] files = Directory.GetFiles(path);
            foreach (string f in files)
            {
                PopupMenuFileItem fitem = new PopupMenuFileItem(f);
                item.DropDown.Items.Add(fitem);
                fitem.RootDropDown = item.RootDropDown;
            }
        }


        protected void resolvePath(string path)
        {
            FileInfo fi = new FileInfo(path);
            this.Text = fi.Name;
        }

        public bool referenceEquals(PopupMenuItem item)
        {
            return object.ReferenceEquals(item, this);
        }

        protected void whenMouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                this.ClickedMouseEventArgs =
                    new MouseEventArgs(e.Button, e.Clicks, e.X, e.Y, e.Delta);
                ((PopupMenu)this.Owner).ItemClickedButton = e.Button;
                //Object o = ((PopupMenu)this.Owner).OwnerItem;
            }
            catch (System.InvalidCastException )
            { }
        }

        virtual protected void whenClicked(object sender, EventArgs e)
        {
            try
            {
                this.RootDropDown.PopupMenuItemMouseClick(this, this.ClickedMouseEventArgs);
            }
            catch
            {
            }
        }

    }
}
